package com.gzhryc.shared_device.oem.h5.mng.controllers.market.cloud;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.net_marketing.cloud.business.dao.db.MarketSupplier;
import com.gzhryc.net_marketing.cloud.business.dao.enums.MarketSupplierEnum;
import com.gzhryc.net_marketing.cloud.business.services.MarketSupplierService;
import com.gzhryc.net_marketing.cloud.business.services.dto.MarketSupplierSearch;
import com.gzhryc.net_marketing.cloud.goods.dao.db.CloudGoods;
import com.gzhryc.net_marketing.cloud.goods.services.CloudGoodsService;
import com.gzhryc.net_marketing.cloud.goods.services.dto.CloudGoodsSearch;
import com.gzhryc.net_marketing.core.enums.EGoodsClassify;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.oem.h5.mng.WebConstants;

public class MarketSupplierController {

    @Route(value = { "/market/cloud/supplier/list.html" })
    public String list(HttpServletRequest request) {
        request.setAttribute("stateList", MarketSupplierEnum.State.values());
        return "/market/cloud/supplier/list.html";
    }

    @Route(value = "/market/cloud/supplier/list.data")
    public ListResult<MarketSupplier> listData(HttpServletRequest request) {
        ListResult<MarketSupplier> result = new ListResult<>(DtoConstants.SUCCESS);

        MarketSupplierSearch search = WebUtils.getParameter(request, MarketSupplierSearch.class);
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);

        result.getBody().setTotal(MarketSupplierService.self().countBySearch(search));
        result.getBody().setData(MarketSupplierService.self().findBySearch(search, pageNo, pageLimit));

        if (result.getBody().getTotal() == 0) {
            result.setCode(DtoConstants.NULL_DATA, "暂无数据");
        }

        return result;
    }

    @Route(value = { "/market/cloud/supplier/add.html" })
    public String add(HttpServletRequest request) {
        return "/market/cloud/supplier/edit.html";
    }

    @Route(value = { "/market/cloud/supplier/add.do" })
    public AjaxResult doAdd(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "新增供货商失败");
        MarketSupplier supplier = WebUtils.getParameter(request, MarketSupplier.class);
        try {
            if (MarketSupplierService.self().add(supplier)) {
                result.setCode(DtoConstants.SUCCESS, null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value = { "/market/cloud/supplier/info.html" })
    public String cloudInfo(HttpServletRequest request) {
        Long id = WebUtils.getLong(request, "id");
        if (id != null) {
        	MarketSupplier supplier = MarketSupplierService.self().getById(id);
            if (supplier != null) {
                WebUtils.setAttribute(request, supplier);
                if(StringTools.isNotBlank(supplier.getDbConfig())) {
                    Map<String,Object> dbConfig = JsonTools.fromJson(supplier.getDbConfig());
                    request.setAttribute("dbConfig", dbConfig);
                }
            }
        }
        return "/market/cloud/supplier/info.html";
    }

    @Route(value = { "/market/cloud/supplier/update.do" })
    public AjaxResult doUpdate(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "修改运营商应用失败");
        MarketSupplier supplier = WebUtils.getParameter(request, MarketSupplier.class);
        if (supplier != null) {
            try {
                if (MarketSupplierService.self().updateNotNull(supplier)) {
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }

    @Route(value = { "/market/cloud/supplier/db_config/save.do" })
    public AjaxResult doSaveCloudDbConfig(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "保存应用数据库配置失败");
        Long id = WebUtils.getLong(request, "id");
        Map<String, String> dbConfig = WebUtils.getSingleParameter(request, "dbConfig");
        if (id != null && dbConfig != null) {
            try {
                if (MarketSupplierService.self().updateDbConfig(id, JsonTools.toJson(dbConfig))) {
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }
    
    @Route(value = { "/market/cloud/supplier/state/update.do" })
    public AjaxResult doEnable(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "修改失败");
        Long id = WebUtils.getLong(request, "id");
        if (id != null) {
            try {
                if (MarketSupplierService.self().toSwitchState(id)) {
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }

    @Route(value = { "/market/cloud/supplier/goods/list.html" })
	public String cloudList(HttpServletRequest request) {
		request.setAttribute("classifyList", EGoodsClassify.values());
		return "/market/cloud/supplier/goods.html";
	}
	
	@Route(value = "/market/cloud/supplier/goods/list.data")
	public ListResult<CloudGoods> cloudGoodsListData(HttpServletRequest request) {
		ListResult<CloudGoods> result = new ListResult<CloudGoods>(DtoConstants.NULL_DATA,"暂无数据");
		CloudGoodsSearch search = WebUtils.getParameter(request, CloudGoodsSearch.class);
		if(search.getSupplierId() != null) {
			Integer pageNo = WebUtils.getInteger(request, "page", 1);
			Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);
			
			result.getBody().setTotal(CloudGoodsService.self().countBySearch(search));
			List<CloudGoods> goodsList = CloudGoodsService.self().findBySearch(search, pageNo, pageLimit);
			if(goodsList != null && goodsList.size() > 0){
				result.setCode(DtoConstants.SUCCESS, null);
				result.getBody().setData(new ArrayList<>());
				String resDomain = PropertyTools.get().getString("marketResDomain");
				for(CloudGoods goods : goodsList){
					//图片路径
					if (StringTools.isNotBlank(goods.getDetailImgs())) {
						String[] detailImgArray = goods.getDetailImgPaths();
						if (detailImgArray != null && detailImgArray.length > 0) {
							for (int i = 0; i < detailImgArray.length; i++) {
								detailImgArray[i] = WebUtils.setHttpDomain(resDomain, detailImgArray[i]);
							}
							goods.setDetailImgs(StringUtils.join(detailImgArray, "|"));
						}
					}
					if (StringTools.isNotBlank(goods.getImgs())) {
						String[] imgArray = goods.getImgPaths();
						if (imgArray != null && imgArray.length > 0) {
							for (int i = 0; i < imgArray.length; i++) {
								imgArray[i] = WebUtils.setHttpDomain(resDomain, imgArray[i]);
							}
							goods.setImgs(StringUtils.join(imgArray, "|"));
						}
					}
					goods.setThumbnailImg(WebUtils.setHttpDomain(resDomain, goods.getThumbnailImg()));
					result.getBody().getData().add(goods);
				}
			}
		}
		return result;
	}
    
    @Route(value = { "/market/cloud/supplier/del.do" })
    public AjaxResult doDel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "删除运营商应用失败");
        Long id = WebUtils.getLong(request,"id");
        try {
            if (MarketSupplierService.self().deleteById(id)) {
                result.setCode(DtoConstants.SUCCESS, null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }
}
